import { stringify } from 'querystring'
import { useSelector } from 'react-redux'
import { AppState, useAppDispatch } from 'state'
import { changeName, init } from './slice'

/**
 * 可以看出hooks 就是一个函数，使用use 开头
 * react 规定使用use 开通的函数为hooks, 以区分普通，因此如果是自定义hooks,必须以use开头
 */

export const useTestName = () => {
    // 返回一个值
    return useSelector((state: AppState) => state.test.name)
}
export const useTestAge = () => {
    return useSelector((state: AppState) => state.test.age)
}

// 把业务逻辑封装到一个函数，实现业务逻辑的共用
// 返回一个函数，这里利用闭包实现函数式编程
export const useChangeName = () => {
    const dispatch = useAppDispatch()

    const setName = (name: string) => {
        dispatch(changeName(name))
    }
    return setName
}
export const useInitTest = () => {
    const dispatch = useAppDispatch()
    return ({ name, age }: { name: string, age: number }) => {
        dispatch(init({ name, age }))
    }
}
